package breadbox.client.logging;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;

import breadbox.client.files.Chunk;

/**
 * This class takes care of the file output for the log
 * @author Forrest
 *
 */
public class LogFileOutput {
	private FileOutputStream fileOut;
	private ObjectOutputStream objectOut;
	
    /**
     * Construct a new FileOutput instance
     * @param filename String filename of output file
     */
	public LogFileOutput(String filename){
		try {
		    this.fileOut = new FileOutputStream(Log.LOG_DIRECTORY + "/" + filename + Log.LOG_FILE_EXTENSION);
		    this.objectOut = new ObjectOutputStream(fileOut);
	    } catch (FileNotFoundException e) {
	    	System.err.println("Log error: Log file not found");
	    } catch (IOException e) {
	    	System.err.println("Log error: Cannot open log file");
	    }
	}

	/**
	 * Write a list of chunks to the current output
	 * @param chunks
	 * @throws IOException
	 */
	public void writeChunks(List<Chunk> chunks) throws IOException {
		for (Chunk k : chunks) {
			writeChunk(k);
		}
	}
	
	/**
	 * Write an array of bytes to the output stream
	 * @param b byte[] to write
	 * @throws IOException errors from FileOutputStream
	 */
	public void writeBytes(byte[] b) throws IOException {
		fileOut.write(b);
	}
	
	/**
	 * Write a chunk to the output stream
	 * @param k Chunk to send out
	 * @throws IOException errors from FileOutputStream
	 */
	public void writeChunk(Chunk k) throws IOException {
		objectOut.writeObject(k);
	}
	
	/**
	 * Close the output streams
	 */
	public void close() throws IOException {
		objectOut.close();
		fileOut.close();
	}
}

